package com.befirefly.studentmanager.handler;

import com.befirefly.studentmanager.entity.AdminDo;
import com.befirefly.studentmanager.service.impl.AdminServiceImpl;
import com.befirefly.studentmanager.view.LoginView;
import com.befirefly.studentmanager.view.MainView;
import org.apache.commons.lang3.StringUtils;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

/**
 * @Author: 八千里路云和月
 * @Date: 2021/2/7 18:06
 * @Description:
 */
public class LoginHandler extends KeyAdapter implements ActionListener {

    private LoginView loginView;

    public LoginHandler(LoginView loginView) {
        this.loginView = loginView;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton jButton = (JButton) e.getSource();
        String text = jButton.getText();
        if ("重置".equals(text)) {
            loginView.getUserTxt().setText("");
            loginView.getPwdField().setText("");
        } else if ("登录".equals(text)) {
            login();
        }
    }

    private void login() {
        String user = loginView.getUserTxt().getText();
        char[] chars = loginView.getPwdField().getPassword();
        if (chars == null || StringUtils.isBlank(user)) {
            JOptionPane.showMessageDialog(loginView, "用户名或密码不能为空！");
            return;
        }
        String pwd = new String(chars);
        System.out.println(user + ":" + pwd);
        // 查询db
        AdminDo adminDo = new AdminDo();
        adminDo.setUsername(user);
        adminDo.setPwd(pwd);
        AdminServiceImpl adminService = new AdminServiceImpl();
        System.out.println(LoginHandler.class.getClassLoader().getResource("").getPath());
        boolean flag = adminService.validateAdmin(adminDo);
        if (flag) {
            // 跳转到主界面并销毁登陆界面
            new MainView();
            loginView.dispose();
        } else {
            JOptionPane.showMessageDialog(loginView, "用户名密码错误！");
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if (KeyEvent.VK_ENTER == e.getKeyCode()) {
            login();
        }
    }
}
